#! /usr/bin/python
# This code warps the IHWarpNewQ shell script

import subprocess
import sys
import os

def slave_action(target_img, object_img, log_file):
    # call the IHWarpNewQ with the target, object images and log file 

    if isinstance(log_file,str):
        log_file_name=log_file
    else:
        try:
            log_file_name=log_file.handlers[-1].baseFilename
        except: 
            log_file_name="coreglog" 

    try:
        subprocess.check_call([os.path.expanduser('~/FXTAS/bin/IHWarpNewQ'),target_img, object_img, "log="+log_file_name, "level=2"])
    except:
        return "JOB_FAILED"
    else:
        return "JOB_DONE"

if __name__=='__main__':
    # parse the argument to get the target and object file names 
    # create log file and call slave_action 

    if len(sys.argv) < 3:
       print 'usage'
       print '-----'
       print 'cubic_spline_warp target object [log_file]'
       print ''
       sys.exit(1)

    target=sys.argv[1]
    if not os.path.exists(target):
       raise Exception('target image does not exists.')  

    object=sys.argv[2]
    if not os.path.exists(object):
       raise Exception('object image does not exists.')  
    
    try:
        log_file=sys.argv[3]
    except IndexError:
        log_file='cubic_spline_warp.log'

    slave_action(target, object, log_file)
